package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    //创建一个线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
    //创建代理对象
    private IVoucherOrderService proxy;
    //在类加载时初始化线程池
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.execute(new VoucherOrderHandler());
    }
    private String queueName="stream.orders";

    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    //1.从消息队列读取订单，XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    //2.判断读取列表里是否有订单
                    if(list==null||list.isEmpty()){
                        continue;
                    }
                    //3。解析消息中的订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //4.获取成功，下单
                    handleVoucherOrder(voucherOrder);
                    //进行ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.info("处理订单引发异常",e);
                    handlePendingList();
                }

            }
        }
    }
    private void handlePendingList() {
        while (true){
            try {
                //1.从消息队列读取订单，XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0")));
                //2.判断读取列表里是否有订单
                if(list==null||list.isEmpty()){
                    break;
                }
                //3。解析消息中的订单信息
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                //4.获取成功，下单
                handleVoucherOrder(voucherOrder);
                //进行ACK确认 SACK stream.orders g1 id
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
            } catch (Exception e) {
                log.info("处理订单引发异常",e);
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }

        }
    }

    /*//创建一个阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
    //创建一个内部类来执行任务
    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //从阻塞队列中获取订单
                    VoucherOrder voucherOrder=orderTasks.take();
                    //创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.info("处理订单引发异常",e);
                }

            }
        }
    }*/

    //创建订单流程
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户id
        Long userId=voucherOrder.getUserId();
        //创建锁对象
        RLock lock=redissonClient.getLock("lock:order:"+userId);
        //获取锁
        boolean isLock=lock.tryLock();
        if(!isLock){
            //获取锁失败，直接返回
            log.info("不允许重复下单");
            return;
        }
        try {
            //执行下单
            proxy.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }

    }

    //创建静态lua脚本资源
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId=UserHolder.getUser().getId();
        long orderId= redisIdWorker.nextId("order");
        //1执行lua脚本
        Long result=stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),userId.toString(),String.valueOf(orderId) );
        int r=result.intValue();

        //2判断结果是否为0
        if(r!=0){
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }
        //由于子线程无法直接获取父线程的代理对象，所以需要在类中直接生命代理，然后在这个为代理赋值
        //创建代理对象
        proxy=(IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

/*    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId=UserHolder.getUser().getId();
        //1执行lua脚本
        Long result=stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),userId.toString() );
        int r=result.intValue();

        //2判断结果是否为0
        if(r!=0){
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }
        //3为0，将订单id保存到消息阻塞队列
        long orderId=redisIdWorker.nextId("order");
        //TODO 保存阻塞队列
        VoucherOrder voucherOrder=new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //放入阻塞队列
        orderTasks.add(voucherOrder);
        //由于子线程无法直接获取父线程的代理对象，所以需要在类中直接生命代理，然后在这个为代理赋值
        //创建代理对象
        proxy=(IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }*/

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //1判断是否开始
        //先获取秒杀卷
        SeckillVoucher seckillVoucher=seckillVoucherService.getById(voucherId);
        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀活动尚未开始");
        }
        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀活动已经结束");
        }
        //2判断库存是否充足
        if(seckillVoucher.getStock()<1){
            return Result.fail("库存不足");
        }
        Long userid= UserHolder.getUser().getId();
        //原来的用synchronized实现一人一锁在一个用户向多台服务器发送时，不同的服务器有各自的jvm虚拟机锁监视器
        //导致可以在不同的jvm虚拟机中同时获取锁，所以需要使用分布式锁
        *//*synchronized (userid.toString().intern()) {
            //因为方法直接调用其实是对象自己this调用方法而非spring代理对象进行调用方法，
            //而事务的执行是由spring的代理对象进行调用，所以需要使用代理对象进行调用
            //代理对象调用方法，事务才会生效
            //创建代理对象
            IVoucherOrderService proxy=(IVoucherOrderService) AopContext.currentProxy();
            //由于代理对象没有该方法，所以需要在service层接口创建该方法
            return proxy.createVoucherOrder(voucherId);
//            return createVoucherOrder(voucherId);
        }*//*
        //使用分布式锁
//        SimpleRedisLock simpleRedisLoc=new SimpleRedisLock("order:"+userid, stringRedisTemplate);
        //改用redisson锁
        RLock lock=redissonClient.getLock("lock:order:"+userid);
        //默认无参是不重新获取锁，30s自动释放
        boolean isLock=lock.tryLock();
//        boolean isLock=simpleRedisLoc.tryLock(1000);
        //判断是否获取锁成功
        if(!isLock){
            return Result.fail("一个用户只能下一单");
        }
        try {
            //创建代理对象
            IVoucherOrderService proxy=(IVoucherOrderService) AopContext.currentProxy();
            //由于代理对象没有该方法，所以需要在service层接口创建该方法
            return proxy.createVoucherOrder(voucherId);
        } finally {
//            simpleRedisLoc.unlock();
            lock.unlock();
        }

    }*/

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder){
        //一人一单，判断用户是否已经买过
        long userid= voucherOrder.getUserId();
        int count= query().eq("user_id",userid).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count>0){
            log.info("不允许重复下单");
            return;
        }
        //3扣减库存
        boolean success=seckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0).update();
        //判断是否扣减成功
        if(!success){
            log.info("库存不足");
            return ;
        }
        save(voucherOrder);
    }

    /*@Override
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //一人一单，判断用户是否已经买过
        long userid= UserHolder.getUser().getId();
        int count= query().eq("user_id",userid).eq("voucher_id", voucherId).count();
        if(count>0){
            return Result.fail("一人只能购买一单!");
        }
        //3扣减库存
        boolean success=seckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id", voucherId)
                .gt("stock",0).update();
        //判断是否扣减成功
        if(!success){
            return Result.fail("库存不足");
        }
        //创建优惠卷订单
        VoucherOrder voucherOrder=new VoucherOrder();
        //设置订单id，优惠卷id，用户id，其中订单id就是之前需要创建的全局唯一id
        long orderId= redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        save(voucherOrder);


        return Result.ok(orderId);
    }*/
}
